<template>
  <div>
    <el-dialog
      :title="dialogData.editTitle"
      :before-close="handleClose"
      :visible.sync="centerDialogVisible"
      :width="dialogWidth"
      center>
      <div class="dialog-edit-form">
        <el-form :model="form" inline label-position="right" ref="formRef"
          label-width="100px" :rules="rules" :disabled="dialogData.editType === 'view'">
          <el-row>
            <el-col :span="24">
              <el-form-item label="上级菜单" prop="parentId">
                <!-- <el-input v-model="form.parentId" autocomplete="off" placeholder="上级菜单"></el-input> -->
                <el-cascader
                  ref="cascader"
                  v-model="form.parentId"
                  :options="options"
                  :props="{ checkStrictly: true }"
                  @change="handleChange">
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="菜单类型" prop="type">
                <el-radio-group v-model="form.type">
                  <el-radio-button :label="12801001">目录</el-radio-button>
                  <el-radio-button :label="12801002">菜单</el-radio-button>
                  <el-radio-button :label="12801003">按钮</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" :xs="24" >
              <el-form-item label="菜单名称" prop="name">
                <el-input v-model="form.name" autocomplete="off" placeholder="菜单名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :xs="24">
              <el-form-item prop="permission">
                <span slot="label">
                  <span class="form-label-with-tooltip">
                    <span>权限标识</span>
                    <el-tooltip placement="top" content="Controller中定义的权限，如: @PreAuthorize(`hasAuthority('common:brand:list')`)">
                      <i class="el-icon-question form-label-with-tooltip-icon-pre"></i>
                    </el-tooltip>
                  </span>
                </span>
                <el-input v-model="form.permission" autocomplete="off" placeholder="权限标识"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :xs="24" v-show="form.type !== 12801003">
              <el-form-item label="菜单图标" prop="icon">
                <el-input v-model="form.icon" autocomplete="off" placeholder="菜单图标"
                  :suffix-icon="form.icon" style="width: 206px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :xs="24">
              <el-form-item label="排序" prop="sort">
                <el-input-number v-model="form.sort" label="排序" style="width: 150px"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12" :xs="24" v-show="form.type !== 12801003">
              <el-form-item label="组件路径" prop="link">
                <el-input v-model="form.link" autocomplete="off" placeholder="组件地址"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :xs="24">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="状态" style="width: 150px">
                  <el-option label="启用" :value="12781001"></el-option>
                  <el-option label="停用" :value="12781002"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="dialog-edit-form-btn">
          <el-button type="primary" @click="handleConfirm" size="small" v-if="dialogData.editType !== 'view'">确认</el-button>
          <el-button @click="handleCancel" style="margin-left: 20px;" size="small" v-if="dialogData.editType !== 'view'">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'BrandDialog',
  props: {
    dialogData: {
      type: Object,
      default: () => ({})
    },
    form: {
      type: Object,
      default: () => ({})
    },
    centerDialogVisible: {
      type: Boolean,
      default: false
    },
    options: {
      type: Array,
      default: () => ([])
    }
  },
  data () {
    // radio按钮的校验需要单独处理
    var validateRadio = (rule, value, callback) => {
      if (value) {
        // 没选择时value为0
        if (value === 0) {
          callback(new Error('请选择菜单类型'))
        } else {
          callback()
        }
      } else {
        callback(new Error('请选择菜单类型'))
      }
    }
    return {
      param: '',
      rules: {
        parentId: [
          { required: true, message: '请输入上级菜单', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' }
        ],
        type: [
          { required: true, validator: validateRadio, trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ]
      },
      dialogWidth: '450px'
    }
  },
  mounted () {
    // 根据当前窗口宽度改变弹窗的宽度
    if (document.body.clientWidth < 700) {
      this.dialogWidth = '80%'
    } else {
      this.dialogWidth = '700px'
    }
    this.form.type = 12801001
  },
  watch: {
    form: {
      handler: function (val) {
        // 新增场景默认菜单类型选中目录12801001
        // if (val.id === 0) {
        //   this.form.type = 12801001
        // }
      },
      deep: true
    }
  },
  methods: {
    // 仅当用户通过点击关闭图标或遮罩关闭 Dialog 时起效
    handleClose () {
      this.resetAndEmit('close')
    },
    // 确定
    handleConfirm () {
      // 表单验证
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          let { id, parentId, name, icon, link, type, sort, status, permission } = this.form
          let paramsAdd = {
            parentId, name, icon, link, type, sort, status, permission
          }
          let paramsUpdate = {
            id, parentId, name, icon, link, type, sort, status, permission
          }
          let param = this.dialogData.editType === 'edit' ? paramsUpdate : paramsAdd
          // console.log(param)
          if (this.dialogData.editType === 'edit') {
            this.$apis.updateMenu(param).then(res => {
              // console.log(res)
              if (res && res.code === '200') {
                // 通过验证请求接口
                this.$notify({
                  title: '成功',
                  message: '编辑成功',
                  type: 'success'
                })
                this.resetAndEmit('confirm')
              } else {
                this.$notify.error({
                  title: '错误',
                  message: res.message
                })
              }
            }).catch(err => {
              console.log(err)
              this.$notify.error({
                title: '错误',
                message: '请求异常'
              })
            })
          } else {
            this.$apis.createMenu(param).then(res => {
              // console.log(res)
              if (res && res.code === '200') {
                // 通过验证请求接口
                this.$notify({
                  title: '成功',
                  message: '新增成功',
                  type: 'success'
                })
                this.resetAndEmit('confirm')
              } else {
                this.$notify.error({
                  title: '错误',
                  message: res.message
                })
              }
            }).catch(err => {
              console.log(err)
              this.$notify.error({
                title: '错误',
                message: '保存成功'
              })
            })
          }
        } else {
          return false
        }
      })
    },
    // 取消
    handleCancel () {
      this.resetAndEmit('cancel')
    },
    // 清空表单并且传递通信父组件
    resetAndEmit (val) {
      // 清空数据在父组件中完成
      // this.$refs['formRef'].resetFields()
      // 清空表单验证
      this.$refs['formRef'].clearValidate()
      // 传给父组件通信数据
      let obj = {
        centerDialogVisible: false,
        event: val
      }
      this.$emit('handleEvent', obj)
    },
    // 上级ID改变事件
    handleChange (value) {
      // console.log(value)
      let node = this.$refs['cascader'].getCheckedNodes()
      // console.log(node[0].value)
      // 赋值form.parentId
      this.form.parentId = node[0].value
    }
  }
}
</script>

<style scoped>
  /* input前的label标签加粗 */
  /deep/ .el-form-item__label {
    font-size: 14px;
    color: #333;
    font-weight: 700;
  }

  /* dialog标题从居中变成靠左 */
  /deep/ .el-dialog--center {
    text-align: left
  }

</style>
